<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="概述 什么场景下该使用什么垃圾回收策略？ 垃圾回收发生在哪些区域？ 对象在什么时候能够被回收？  什么场景下该使用什么垃圾回收策略？ 场景一：在对内存要求苛刻的场景：想办法提高对象的回收效率，多回收掉一些对象，腾出更多内存； 场景二：在CPU 使用率高的场景下：降低高并发垃圾回收的频率，让 CPU 更多地去执行你的业务而不是垃圾回收；  垃圾回收发生在哪些区域？JVM 内存结构如下图所示：   虚">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM 垃圾回收">
<meta property="og:url" content="http://littlefxc.github.io/2022/03/01/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="概述 什么场景下该使用什么垃圾回收策略？ 垃圾回收发生在哪些区域？ 对象在什么时候能够被回收？  什么场景下该使用什么垃圾回收策略？ 场景一：在对内存要求苛刻的场景：想办法提高对象的回收效率，多回收掉一些对象，腾出更多内存； 场景二：在CPU 使用率高的场景下：降低高并发垃圾回收的频率，让 CPU 更多地去执行你的业务而不是垃圾回收；  垃圾回收发生在哪些区域？JVM 内存结构如下图所示：   虚">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301152640105.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301153530892.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301154408408.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301162604333.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301163844090.png">
<meta property="article:published_time" content="2022-02-28T23:15:03.000Z">
<meta property="article:modified_time" content="2022-05-10T01:24:19.919Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="jvm">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301152640105.png">


<link rel="canonical" href="http://littlefxc.github.io/2022/03/01/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>JVM 垃圾回收 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E5%9C%BA%E6%99%AF%E4%B8%8B%E8%AF%A5%E4%BD%BF%E7%94%A8%E4%BB%80%E4%B9%88%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AD%96%E7%95%A5%EF%BC%9F"><span class="nav-text">什么场景下该使用什么垃圾回收策略？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E5%8F%91%E7%94%9F%E5%9C%A8%E5%93%AA%E4%BA%9B%E5%8C%BA%E5%9F%9F%EF%BC%9F"><span class="nav-text">垃圾回收发生在哪些区域？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E5%9C%A8%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E8%83%BD%E5%A4%9F%E8%A2%AB%E5%9B%9E%E6%94%B6%EF%BC%9F"><span class="nav-text">对象在什么时候能够被回收？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E6%B3%95"><span class="nav-text">引用计数法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E8%BE%BE%E6%80%A7%E5%88%86%E6%9E%90"><span class="nav-text">可达性分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#GC-Roots-%E5%8C%85%E6%8B%AC%E5%93%AA%E4%BA%9B%E5%AF%B9%E8%B1%A1"><span class="nav-text">GC Roots 包括哪些对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%82%A3%E4%BB%80%E4%B9%88%E6%98%AF%E5%BC%95%E7%94%A8%EF%BC%9F"><span class="nav-text">那什么是引用？</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%BC%BA%E5%BC%95%E7%94%A8"><span class="nav-text">强引用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E8%BD%AF%E5%BC%95%E7%94%A8"><span class="nav-text">软引用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%BC%B1%E5%BC%95%E7%94%A8"><span class="nav-text">弱引用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E8%99%9A%E5%BC%95%E7%94%A8"><span class="nav-text">虚引用</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E8%BE%BE%E6%80%A7%E5%88%86%E6%9E%90%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="nav-text">可达性分析注意点</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%80%E4%B8%AA%E5%AF%B9%E8%B1%A1%E5%8D%B3%E4%BD%BF%E4%B8%8D%E5%8F%AF%E8%BE%BE%EF%BC%8C%E4%B9%9F%E4%B8%8D%E4%B8%80%E5%AE%9A%E4%BC%9A%E8%A2%AB%E5%9B%9E%E6%94%B6"><span class="nav-text">一个对象即使不可达，也不一定会被回收</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E6%BC%94%E7%A4%BA%EF%BC%9A"><span class="nav-text">代码演示：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#finalize-%E7%9A%84%E5%BB%BA%E8%AE%AE"><span class="nav-text">finalize() 的建议</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2022/03/01/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JVM 垃圾回收
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-03-01 07:15:03" itemprop="dateCreated datePublished" datetime="2022-03-01T07:15:03+08:00">2022-03-01</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-10 09:24:19" itemprop="dateModified" datetime="2022-05-10T09:24:19+08:00">2022-05-10</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><ul>
<li>什么场景下该使用什么垃圾回收策略？</li>
<li>垃圾回收发生在哪些区域？</li>
<li>对象在什么时候能够被回收？</li>
</ul>
<h2 id="什么场景下该使用什么垃圾回收策略？"><a href="#什么场景下该使用什么垃圾回收策略？" class="headerlink" title="什么场景下该使用什么垃圾回收策略？"></a>什么场景下该使用什么垃圾回收策略？</h2><ul>
<li>场景一：在对内存要求苛刻的场景：想办法提高对象的回收效率，多回收掉一些对象，腾出更多内存；</li>
<li>场景二：在CPU 使用率高的场景下：降低高并发垃圾回收的频率，让 CPU 更多地去执行你的业务而不是垃圾回收；</li>
</ul>
<h2 id="垃圾回收发生在哪些区域？"><a href="#垃圾回收发生在哪些区域？" class="headerlink" title="垃圾回收发生在哪些区域？"></a>垃圾回收发生在哪些区域？</h2><p>JVM 内存结构如下图所示：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301152640105.png" alt="JVM内存结构"></p>
<ul>
<li>虚拟机栈、本地方法栈、程序计数器是线程隔离的，这 3 个区域与线程的生命周期保持一致，同生共死，是不需要考虑垃圾回收的。</li>
<li>堆和方法区市线程共享的，才需要考虑。</li>
</ul>
<h2 id="对象在什么时候能够被回收？"><a href="#对象在什么时候能够被回收？" class="headerlink" title="对象在什么时候能够被回收？"></a>对象在什么时候能够被回收？</h2><p>就目前来说，有两种算法区判断算法什么时候回收。</p>
<h3 id="引用计数法"><a href="#引用计数法" class="headerlink" title="引用计数法"></a>引用计数法</h3><p>通过对象的引用计数器来判断对象是否被引用；</p>
<p>如下图所示，对象被引用一次，计数器就加 1 ，但是一旦遇到有循环引用的情况，对象就无法被回收。</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301153530892.png" alt="image-20220301153530892"></p>
<h3 id="可达性分析"><a href="#可达性分析" class="headerlink" title="可达性分析"></a>可达性分析</h3><p>Java并没有采用引用计数法，而是使用了可达性分析。</p>
<p>可达性分析：以根对象（GC Roots）作为起点向下搜索，走过的路径被称为引用链（Reference Chain），如果某个对象到根对象没有引用链相连时，就认为这个对象是不可大的，可以被回收。</p>
<p>如下图所示：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301154408408.png" alt="可达性分析"></p>
<h4 id="GC-Roots-包括哪些对象"><a href="#GC-Roots-包括哪些对象" class="headerlink" title="GC Roots 包括哪些对象"></a>GC Roots 包括哪些对象</h4><ul>
<li>虚拟机栈（栈帧中的本地变量表）中引用的对象</li>
<li>方法区中类静态属性引用的对象</li>
<li>方法区中常量引用的对象</li>
<li>本地方法栈中JNI（即 native 方法）引用的对象</li>
</ul>
<h4 id="那什么是引用？"><a href="#那什么是引用？" class="headerlink" title="那什么是引用？"></a>那什么是引用？</h4><h5 id="强引用"><a href="#强引用" class="headerlink" title="强引用"></a>强引用</h5><ul>
<li>形如 <code>Object obj = new Object()</code> 的引用</li>
<li>只要强引用在，永远不会回收被引用的对象，哪怕是内存溢出</li>
</ul>
<h5 id="软引用"><a href="#软引用" class="headerlink" title="软引用"></a>软引用</h5><ul>
<li>形如 <code>SoftReference&lt;String&gt; str = new SoftReference&lt;String&gt;(&quot;hello&quot;)</code></li>
<li>是用来描述一些有用但非必需的对象</li>
<li>软引用关联的对象只有在内存不足的时候才会回收</li>
</ul>
<h5 id="弱引用"><a href="#弱引用" class="headerlink" title="弱引用"></a>弱引用</h5><ul>
<li>形如 <code>WeakReference&lt;String&gt; str = new WeakReference&lt;String&gt;(&quot;hello&quot;)</code></li>
<li>弱引用也用来描述非必需对象的</li>
<li>被弱引用关联的对象只能生存到下一次垃圾收集发生为止</li>
<li>无论当前内存是否足够,都会回收掉只被弱引用关联的对象</li>
</ul>
<h5 id="虚引用"><a href="#虚引用" class="headerlink" title="虚引用"></a>虚引用</h5><ul>
<li><p>形如</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ReferenceQueue&lt;String&gt; queue = <span class="keyword">new</span> ReferenceQueue&lt;&gt;();</span><br><span class="line">PhantomReference&lt;String&gt; pr = <span class="keyword">new</span> PhantomReference&lt;&gt;(<span class="string">&quot;hello&quot;</span>, queue);</span><br></pre></td></tr></table></figure></li>
<li><p>个对象是否有虚引用的存在,完全不会对其生存时间构成影响,也无法通过虚引用来取得一个对象实例。</p>
</li>
<li><p>为一个对象设置虚引用关联的<strong>唯一目的</strong>只是为了能在这个对象被收集器回收时收到一个系统通知。</p>
</li>
</ul>
<h3 id="可达性分析注意点"><a href="#可达性分析注意点" class="headerlink" title="可达性分析注意点"></a>可达性分析注意点</h3><h4 id="一个对象即使不可达，也不一定会被回收"><a href="#一个对象即使不可达，也不一定会被回收" class="headerlink" title="一个对象即使不可达，也不一定会被回收"></a>一个对象即使不可达，也不一定会被回收</h4><p>即使在可达性分析算法中判定为不可达的对象,也不是“非死不可”的,这时候它们暂时还处于“缓刑”阶段,要真正宣告一个对象死亡,至少要经历两次标记过程：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301162604333.png" alt="image-20220301162604333"></p>
<ul>
<li><p>如果对象在进行可达性分析后发现没有与GC Roots相连接的引用链,那它将会被第一次标记,随后进行一次筛选,筛选的条件是此对象是否有必要执行finalize()方法。假如对象没有覆盖finalize()方法,或者finalize()方法已经被虚拟机调用过,那么虚拟机将这两种情况都视为“没有必要执行”。</p>
</li>
<li><p>如果这个对象被判定为确有必要执行finalize()方法,那么该对象将会被放置在一个名为F-Queue的队列之中,并在稍后由一条由虚拟机自动建立的、低调度优先级的Finalizer线程去执行它们的finalize() 方法。这里所说的“执行”是指虚拟机会触发这个方法开始运行,但并不承诺一定会等待它运行结束。<br>这样做的原因是,如果某个对象的finalize()方法执行缓慢,或者更极端地发生了死循环,将很可能导致F-Queue队列中的其他对象永久处于等待,甚至导致整个内存回收子系统的崩溃。finalize()方法是对象逃脱死亡命运的最后一次机会,稍后收集器将对F-Queue中的对象进行第二次小规模的标记,如果对象要在finalize()中成功拯救自己——只要重新与引用链上的任何一个对象建立关联即可,譬如把自己(this关键字)赋值给某个类变量或者对象的成员变量,那在第二次标记时它将被移出“即将回收”的集合;如果对象这时候还没有逃脱,那基本上它就真的要被回收了。</p>
</li>
</ul>
<h4 id="代码演示："><a href="#代码演示：" class="headerlink" title="代码演示："></a>代码演示：</h4>  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.jvm;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此代码演示了两点:</span></span><br><span class="line"><span class="comment"> * * 1.对象可以在被GC时自我拯救。</span></span><br><span class="line"><span class="comment"> * * 2.这种自救的机会只有一次,因为一个对象的finalize()方法最多只会被系统自动调用一次</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FinalizeEscapeGC</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> FinalizeEscapeGC SAVE_HOOK = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        SAVE_HOOK = <span class="keyword">new</span> FinalizeEscapeGC();</span><br><span class="line">        <span class="comment">//对象第一次成功拯救自己</span></span><br><span class="line">        SAVE_HOOK = <span class="keyword">null</span>;</span><br><span class="line">        System.gc();</span><br><span class="line">        <span class="comment">// 因为Finalizer方法优先级很低,暂停0.5秒,以等待它</span></span><br><span class="line">        Thread.sleep(<span class="number">500</span>);</span><br><span class="line">        <span class="keyword">if</span> (SAVE_HOOK != <span class="keyword">null</span>) &#123;</span><br><span class="line">            SAVE_HOOK.isAlive();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;no, i am dead :(&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 下面这段代码与上面的完全相同,但是这次自救却失败了</span></span><br><span class="line">        SAVE_HOOK = <span class="keyword">null</span>;</span><br><span class="line">        System.gc();</span><br><span class="line">        <span class="comment">// 因为Finalizer方法优先级很低,暂停0.5秒,以等待它</span></span><br><span class="line">        Thread.sleep(<span class="number">500</span>);</span><br><span class="line">        <span class="keyword">if</span> (SAVE_HOOK != <span class="keyword">null</span>) &#123;</span><br><span class="line">            SAVE_HOOK.isAlive();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;no, i am dead :(&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">isAlive</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;yes, i am still alive :)&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finalize</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.finalize();</span><br><span class="line">        System.out.println(<span class="string">&quot;finalize method executed!&quot;</span>);</span><br><span class="line">        FinalizeEscapeGC.SAVE_HOOK = <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>  结果展示：</p>
<p>  <img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220301163844090.png" alt="image-20220301163844090"></p>
<p>事实上假如将代码第24行也就是第二次调用 System.gc() 前没有将SAVE_HOOK 设为 null，那么 SAVE_HOOK 对象将永远不会被回收。</p>
<h4 id="finalize-的建议"><a href="#finalize-的建议" class="headerlink" title="finalize() 的建议"></a>finalize() 的建议</h4><ul>
<li><p>避免使用finalize()方法，操作不当可能会导致问题；</p>
</li>
<li><p>finalize() 优先级低，何时会被调用无法确定，因为什么时间发生 GC 不确定；</p>
</li>
<li><p>建议使用 try…catch…finally来替代 finalize()。 </p>
</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/jvm/" rel="tag"># jvm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/02/28/docs/5G/NIDD/" rel="prev" title="NIDD">
                  <i class="fa fa-chevron-left"></i> NIDD
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/03/01/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95/" rel="next" title="JVM 垃圾回收算法">
                  JVM 垃圾回收算法 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
